<template>
  <view class="container">
    <!-- 空购物车提示 -->
    <view class="empty-cart" v-if="cartItems.length === 0">
      <image src="/static/images/empty-cart.png" mode="aspectFit" class="empty-cart-image"></image>
      <text class="empty-cart-text">购物车还是空的</text>
      <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
    </view>
    
    <!-- 购物车商品列表 -->
    <view class="cart-list" v-else>
      <!-- 编辑按钮 -->
      <view class="edit-header">
        <text class="edit-btn" @click="toggleEdit">{{ isEdit ? '完成' : '编辑' }}</text>
      </view>
      
      <!-- 商品列表 -->
      <view class="cart-items">
        <view class="cart-item" v-for="(item, index) in cartItems" :key="index">
          <!-- 商品选择框 -->
          <checkbox :checked="item.selected" @tap="toggleSelect(index)" class="checkbox"></checkbox>
          
          <!-- 商品图片 -->
          <image :src="item.image" mode="aspectFill" class="item-image" @click="navigateToDetail(item)"></image>
          
          <!-- 商品信息 -->
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-spec" v-if="item.spec">规格：{{ item.spec }}</text>
            <view class="item-bottom">
              <text class="item-price">¥{{ item.price }}</text>
              <!-- 数量控制 -->
              <view class="quantity-control">
                <text class="quantity-btn" @click="decreaseQuantity(index)">-</text>
                <input type="number" v-model="item.quantity" class="quantity-input" @blur="updateQuantity(index)"/>
                <text class="quantity-btn" @click="increaseQuantity(index)">+</text>
              </view>
            </view>
          </view>
          
          <!-- 删除按钮 -->
          <text class="delete-btn" v-if="isEdit" @click="deleteItem(index)">删除</text>
        </view>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="settlement-bar" v-if="cartItems.length > 0">
      <view class="select-all">
        <checkbox :checked="isAllSelected" @tap="toggleSelectAll"></checkbox>
        <text>全选</text>
      </view>
      <view class="total-section">
        <view class="price-section">
          <text>合计：</text>
          <text class="total-price">¥{{ totalPrice }}</text>
        </view>
        <text class="selected-count">已选{{ selectedCount }}件</text>
      </view>
      <button class="settlement-btn" :class="{ 'disabled': selectedCount === 0 }" @click="settlement">
        结算({{ selectedCount }})
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartItems: [],
      isEdit: false,
      isAllSelected: false
    };
  },
  computed: {
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length;
    },
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => total + item.price * item.quantity, 0)
        .toFixed(2);
    }
  },
  onShow() {
    // 每次显示页面时重新获取购物车数据
    this.loadCartItems();
  },
  methods: {
    loadCartItems() {
      const cartItems = uni.getStorageSync('cart') || [];
      this.cartItems = cartItems;
      this.updateAllSelectedStatus();
    },
    toggleEdit() {
      this.isEdit = !this.isEdit;
    },
    toggleSelect(index) {
      this.cartItems[index].selected = !this.cartItems[index].selected;
      this.updateAllSelectedStatus();
      this.saveCartItems();
    },
    toggleSelectAll() {
      this.isAllSelected = !this.isAllSelected;
      this.cartItems.forEach(item => {
        item.selected = this.isAllSelected;
      });
      this.saveCartItems();
    },
    updateAllSelectedStatus() {
      this.isAllSelected = this.cartItems.length > 0 && 
        this.cartItems.every(item => item.selected);
    },
    decreaseQuantity(index) {
      if (this.cartItems[index].quantity > 1) {
        this.cartItems[index].quantity--;
        this.saveCartItems();
      }
    },
    increaseQuantity(index) {
      const item = this.cartItems[index];
      if (item.quantity < item.stock) {
        item.quantity++;
        this.saveCartItems();
      } else {
        uni.showToast({
          title: '超出库存数量',
          icon: 'none'
        });
      }
    },
    updateQuantity(index) {
      let quantity = parseInt(this.cartItems[index].quantity);
      const item = this.cartItems[index];
      
      if (isNaN(quantity) || quantity < 1) {
        quantity = 1;
      } else if (quantity > item.stock) {
        quantity = item.stock;
        uni.showToast({
          title: '已调整为最大库存数量',
          icon: 'none'
        });
      }
      
      this.cartItems[index].quantity = quantity;
      this.saveCartItems();
    },
    deleteItem(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            this.cartItems.splice(index, 1);
            this.saveCartItems();
            this.updateAllSelectedStatus();
            
            // 如果购物车为空，退出编辑模式
            if (this.cartItems.length === 0) {
              this.isEdit = false;
            }
          }
        }
      });
    },
    saveCartItems() {
      uni.setStorageSync('cart', this.cartItems);
    },
    goShopping() {
      uni.switchTab({
        url: '/pages/my/details/details'
      });
    },
    navigateToDetail(item) {
      uni.navigateTo({
        url: `/pages/spxq/detail?productInfo=${encodeURIComponent(JSON.stringify(item))}`
      });
    },
    settlement() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }
      
      const selectedItems = this.cartItems.filter(item => item.selected);
      const orderInfo = {
        items: selectedItems,
        totalPrice: this.totalPrice
      };
      
      uni.navigateTo({
        url: `/pages/order/confirm?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
      });
    }
  }
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
}

.empty-cart-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-cart-text {
  color: #999;
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.go-shopping-btn {
  background-color: #4CAF50;
  color: #fff;
  padding: 20rpx 60rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.edit-header {
  padding: 20rpx;
  text-align: right;
}

.edit-btn {
  color: #4CAF50;
  font-size: 28rpx;
}

.cart-items {
  background: #fff;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.checkbox {
  margin-right: 20rpx;
  transform: scale(0.8);
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.item-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 32rpx;
  color: #4CAF50;
  font-weight: bold;
}

.quantity-control {
  display: flex;
  align-items: center;
  background: #f0fff0;
  border-radius: 6rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #4CAF50;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  background: #fff;
}

.delete-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  color: #4CAF50;
  font-size: 28rpx;
}

.settlement-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.select-all {
  display: flex;
  align-items: center;
}

.select-all text {
  font-size: 28rpx;
  color: #333;
  margin-left: 10rpx;
}

.total-section {
  flex: 1;
  margin-left: 30rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
}

.total-price {
  font-size: 36rpx;
  color: #4CAF50;
  font-weight: bold;
}

.selected-count {
  font-size: 24rpx;
  color: #999;
}

.settlement-btn {
  background-color: #4CAF50;
  color: #fff;
  padding: 0 40rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  margin-left: 20rpx;
}

.settlement-btn.disabled {
  background-color: #a5d6a7;
  opacity: 0.8;
}

.checkbox {
  margin-right: 20rpx;
  transform: scale(0.8);
}

::v-deep .uni-checkbox-input {
  border-color: #4CAF50 !important;
}

::v-deep .uni-checkbox-input.uni-checkbox-input-checked {
  background-color: #4CAF50 !important;
  border-color: #4CAF50 !important;
}
</style> 